<template>
  <div class="store-management">
    <div class="header">
      <h2>门店管理</h2>
      <button @click="$router.push('/dashboard')" class="back-btn">返回首页</button>
    </div>
    
    <!-- 添加门店表单 -->
    <div class="add-store-form">
      <input v-model="newStore.name" placeholder="门店名称" />
      <input v-model="newStore.address" placeholder="详细地址" />
      <input v-model="newStore.phone" placeholder="联系电话" />
      <select v-model="newStore.manager_id">
        <option value="">选择店长</option>
        <option v-for="employee in employees" :key="employee.id" :value="employee.id">
          {{ employee.name }}
        </option>
      </select>
      <button @click="addStore" :disabled="!isValidStore">添加门店</button>
    </div>

    <!-- 门店列表 -->
    <table class="store-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>门店名称</th>
          <th>地址</th>
          <th>电话</th>
          <th>店长</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="store in stores" :key="store.id">
          <td>{{ store.id }}</td>
          <td>{{ store.name }}</td>
          <td>{{ store.address }}</td>
          <td>{{ store.phone }}</td>
          <td>{{ store.manager_name || '未分配' }}</td>
          <td>
            <span :class="['status-badge', store.status === 'active' ? 'open' : 'closed']">
              {{ getStatusName(store.status) }}
            </span>
          </td>
          <td>
            <button @click="editStore(store)">编辑</button>
            <button 
              @click="toggleStoreStatus(store)"
              :class="['status-btn', store.status === 'active' ? 'close' : 'open']"
            >
              {{ store.status === 'active' ? '打烊' : '营业' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 编辑门店对话框 -->
    <div v-if="showEditDialog" class="edit-dialog">
      <div class="edit-dialog-content">
        <h3>编辑门店</h3>
        <div class="form-group">
          <label>门店名称：</label>
          <input v-model="editingStore.name" />
        </div>
        <div class="form-group">
          <label>详细地址：</label>
          <input v-model="editingStore.address" />
        </div>
        <div class="form-group">
          <label>联系电话：</label>
          <input v-model="editingStore.phone" />
        </div>
        <div class="form-group">
          <label>店长：</label>
          <select v-model="editingStore.manager_id">
            <option value="">选择店长</option>
            <option v-for="employee in employees" :key="employee.id" :value="employee.id">
              {{ employee.name }}
            </option>
          </select>
        </div>
        <div class="dialog-buttons">
          <button @click="updateStore">保存</button>
          <button @click="showEditDialog = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'StoreManagement',
  data() {
    return {
      stores: [],
      employees: [],
      newStore: {
        name: '',
        address: '',
        phone: '',
        manager_id: '',
        status: 'active'
      },
      showEditDialog: false,
      editingStore: null
    }
  },
  computed: {
    isValidStore() {
      return this.newStore.name && this.newStore.address && this.newStore.phone
    }
  },
  created() {
    this.fetchStores()
    this.fetchEmployees()
  },
  methods: {
    getStatusName(status) {
      const statusMap = {
        'active': '营业中',
        'inactive': '已打烊',
        '1': '营业中',
        '0': '已打烊'
      }
      return statusMap[status] || status
    },
    async fetchEmployees() {
      try {
        const response = await axios.get('/api/employees', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.employees = response.data
      } catch (error) {
        console.error('获取员工列表失败:', error)
        alert('获取员工列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async fetchStores() {
      try {
        const response = await axios.get('/api/stores', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.stores = response.data
      } catch (error) {
        console.error('获取门店列表失败:', error)
        alert('获取门店列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async addStore() {
      if (!this.isValidStore) {
        alert('请填写完整的门店信息')
        return
      }
      try {
        const storeData = {
          ...this.newStore,
          status: 'active' // 使用字符串状态值
        }
        console.log('添加门店数据:', storeData)
        
        const response = await axios.post('/api/stores', storeData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchStores()
        this.newStore = { 
          name: '', 
          address: '', 
          phone: '', 
          manager_id: '',
          status: 'active'
        }
        alert('添加门店成功')
      } catch (error) {
        console.error('添加门店失败:', error)
        alert('添加门店失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    editStore(store) {
      this.editingStore = { 
        ...store,
        status: store.status === 'active' || store.status === '1' ? 'active' : 'inactive'
      }
      this.showEditDialog = true
    },
    async updateStore() {
      try {
        const storeData = {
          ...this.editingStore,
          status: this.editingStore.status === 'active' || this.editingStore.status === '1' ? 'active' : 'inactive'
        }
        console.log('更新门店数据:', storeData)
        
        await axios.put(`/api/stores/${this.editingStore.id}`, storeData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchStores()
        this.showEditDialog = false
        alert('更新门店成功')
      } catch (error) {
        console.error('更新门店失败:', error)
        alert('更新门店失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async toggleStoreStatus(store) {
      try {
        const newStatus = store.status === 'active' || store.status === '1' ? 'inactive' : 'active'
        console.log('更新门店状态:', { status: newStatus })
        
        await axios.put(`/api/stores/${store.id}/status`, { 
          status: newStatus 
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        this.fetchStores()
        alert(`门店${newStatus === 'active' ? '营业' : '打烊'}成功`)
      } catch (error) {
        console.error('更新门店状态失败:', error)
        alert('更新门店状态失败：' + (error.response?.data?.message || '未知错误'))
      }
    }
  }
}
</script>

<style scoped>
.store-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-store-form {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.store-table {
  width: 100%;
  border-collapse: collapse;
}

.store-table th,
.store-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.store-table th {
  background-color: #f5f5f5;
}

button {
  margin: 0 5px;
  padding: 5px 10px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-badge.open {
  background-color: #67c23a;
  color: white;
}

.status-badge.closed {
  background-color: #f56c6c;
  color: white;
}

.status-btn {
  font-size: 12px;
}

.status-btn.open {
  background-color: #67c23a;
}

.status-btn.close {
  background-color: #f56c6c;
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #909399;
}

.cancel-btn:hover {
  background-color: #a6a9ad;
}
</style> 